package com.epfresh.supplier.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.utils.AppUtils;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;

import static com.epfresh.api.constant.Constant.URL_ORDER_JOINSUPPLIER;
import static com.epfresh.api.constant.Constant.URL_ORDER_SUPPLIER;

import com.epfresh.api.global.*;

import okhttp3.internal.Util;

/**
 * Created by wzh on 2016/5/6.
 */
public class H5OrderDetailActivity extends BaseActivity {
    private WebView webview;
    private ProgressBar pb;
    private String url;
    private String title;
    private int pushType = 2;

    private String orderId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        if (savedInstanceState != null) {
            url = savedInstanceState.getString(Constant.KEY_WEB_URL);
            title = savedInstanceState.getString(Constant.KEY_WEB_TITLE);
            pushType = savedInstanceState.getInt("pushType");
            orderId = savedInstanceState.getString("orderId");
        } else {
            url = getIntent().getStringExtra(Constant.KEY_WEB_URL);
            title = getIntent().getStringExtra(Constant.KEY_WEB_TITLE);
            pushType = getIntent().getIntExtra("pushType", 2);
            orderId = getIntent().getStringExtra("orderId");
        }

        pushType = getIntent().getIntExtra("pushType", 2);
//        if (TextUtils.isEmpty(url)) {
//            finish();
//        } else {
        ivBack.setVisibility(View.VISIBLE);
        toolbarTitle.setVisibility(View.VISIBLE);
        toolbarTitle.setText(title == null ? "" : title);
        pb = (ProgressBar) findViewById(R.id.pb);
        webview = (WebView) findViewById(R.id.wv);
        pb.setVisibility(View.VISIBLE);
        webViewSetting();
        url = getOrderUrl();
        Log.e("url:", url);
        if (!TextUtils.isEmpty(url)) {
            webview.loadUrl(url);
        } else {
            toast("数据错误请重试！");
            finish();
        }
//        }

    }

    public String getOrderUrl() {
        if (!url.contains("http://mtest.epfresh.com/cntest/supply/order_supply_joint.html?goodId=")) {
            String requrl = URL_ORDER_SUPPLIER;
/*        String token = getUser().getToken();
        String accountId = getUser().getAccountId();
        String cityId = ApplicationHelper.getInstance().getCity().getCityId();
        url = url + "token=" + token + "&supplyId=" + accountId + "&cityId=" + cityId + "&orderId=" + orderId;*/
            String token = getUser().getAccess_token();
/*        if(getStoreInfo()==null||getStoreInfo().getStore()==null){
            return url;
        }*/
            String storeId = BaseApplication.getInstance().getStoreId();
            String cityId = ApplicationHelper.getInstance().getCity().getCityId();
            url = requrl + "access_token=" + token + "&storeId=" + storeId + "&cityId=" + cityId + "&orderId=" + orderId;
            url += "&cid=" + AppUtils.getUniquePsuedoID();

        } else {
            String requrl = URL_ORDER_JOINSUPPLIER;
/*        String token = getUser().getToken();
        String accountId = getUser().getAccountId();
        String cityId = ApplicationHelper.getInstance().getCity().getCityId();
        url = url + "token=" + token + "&supplyId=" + accountId + "&cityId=" + cityId + "&orderId=" + orderId;*/
            String token = getUser().getAccess_token();
/*        if(getStoreInfo()==null||getStoreInfo().getStore()==null){
            return url;
        }*/
            String storeId = BaseApplication.getInstance().getStoreId();
            url = requrl + "access_token=" + token + "&storeId=" + storeId + "&orderId=" + orderId;
            url += "&cid=" + AppUtils.getUniquePsuedoID();
        }
        return url;
    }


    public void webViewSetting() {
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互

//        settings.setAppCachePath(cacheDirPath); //设置缓存的指定路径
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//https 页面里面有http形式的图片地址
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webview.setBackgroundColor(Color.TRANSPARENT);
        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 99) {
                    pb.setVisibility(View.GONE);
                } else {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);
                    pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (title != null && !"".equals(title))
                    toolbarTitle.setText(title);
            }
        });
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("url", "url:" + url);
                if (url != null && url.startsWith("epfreshsupplierclick://followorder") && mContext != null) {
                    Intent intent = new Intent(mContext, OrderLogisticsInfoActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    intent.putExtra("logisticsNo", id);
                    startActivity(intent);
                    Log.e(")_____________________", id);
                    return true;
                } else if (url != null && url.startsWith("epfreshsupplierclick://iden") && mContext != null) {
                    Intent ensure = new Intent(mContext, OrderEnsureActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    ensure.putExtra("id", id);
                    startActivityForResult(ensure, 0x002);//0,修改；1，发货物流；2，确认；3，申诉；
                    Log.e(")_____________________", id);
                    return true;
                } else if (url != null && url.startsWith("epfreshsupplierclick://minusdown") && mContext != null) {
                    Intent intent = new Intent(mContext, OrderMinusRecordActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    intent.putExtra("id", id);
                    startActivity(intent);
                    Log.e(")________fadsf____", id);
                    return true;
                } else if (url != null && url.startsWith("epfreshsupplierclick://minus") && mContext != null) {
                    Intent minus = new Intent(mContext, OrderMinusActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    minus.putExtra("id", id);
                    minus.putExtra("saleUnit", Uri.parse(url).getQueryParameter("price"));
                    minus.putExtra("costSum", Uri.parse(url).getQueryParameter("goodMoney"));
                    minus.putExtra("productNumber", Uri.parse(url).getQueryParameter("goodNumber"));
                    startActivityForResult(minus, 0x003);//0,修改；1，发货物流；2，确认；3，申诉；
                    Log.e(")_____________________", id);
                    return true;
                } else if (url != null && url.startsWith("epfreshsupplierclick://loginexc")) {//登陆异常
                    Intent intent = new Intent(mContext, LoginActivity.class);
//                    intent.putExtra("relogin", true);
                    intent.putExtra("backLast", true);
                    startActivityForResult(intent, 0x001);
                    return true;
                } else if (url != null && url.startsWith("tel:")) {//电话
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url != null && url.startsWith("epfreshsupplierclick://actuclmatch") && mContext != null) {
                    String goodid = Uri.parse(url).getQueryParameter("goodId");
                    if (TextUtils.isEmpty(goodid)) goodid = url.split("goodId:")[1];
                    startActivity(new Intent(mContext, JoinPrepareGridActivity.class).putExtra("goodId", goodid));
                    Log.e("拦截url", url);
                    return true;
                }/*else {
                    view.loadUrl(url);
                }*/
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public void onLoadResource(WebView view, String url) {

            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }
        });

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (outState == null) {
            outState = new Bundle();
        }
        outState.putString(Constant.KEY_WEB_URL, url);
        outState.putString(Constant.KEY_WEB_TITLE, title);
        outState.putInt("pushType", pushType);
        outState.putString("orderId", orderId);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        if (reloadFlag) {
            setResult(0x002);
            finish();
        }
        if (webview.canGoBack()) {
            webview.goBack();
            basetitle.setText("订单详情");
        } else if (pushType == 0) {
            Intent main = new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(main);
            finish();
        } else if (pushType == 1) {
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View view) {
        //super.onClick(view);
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                onBackPressed();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        super.onDestroy();
    }

    boolean reloadFlag;

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent date) {
        super.onActivityResult(requestcode, resultcode, date);
        if (requestcode == 0x001 && resultcode == RESULT_OK) {
            webview.reload();
            return;
        }
        switch (resultcode) {
            case 0x000:
            case 0x001:
            case 0x002:
            case 0x003:
            case 0x004:
            case 0x005:
                reloadFlag = true;
                webview.loadUrl(url);
                break;
        }
    }
}
